import { Table, Pagination, Space, Button, Tooltip, DatePicker, Select, TimePicker, Input } from 'antd';
import { ReloadOutlined, ClearOutlined, SettingOutlined, SearchOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';

/**
 * props = {
 *   columns = [],
 *   data = [],
 *   selected = [],
 *   isPage = true,
 *   pagination = {},
 *   onReload,
 *   onSelected,
 *   toolbar = undefined,
 *   isTools = true,
 * } = useTable();
 * 
 */

const CloudTable = ({ props }) => {

    const { columns, data, selected, isPage, pagination, onReload, resetSelected, showTools, tools } = props;
    
    // 表格中的数据条数，用于表格滚动计算
    const [count, setCount] = useState(0);
    // 表格列
    const [items, setItems] = useState([]);
    // 表格滚动
    const [scroll, setScroll] = useState({ x: props?.width || undefined, y: props?.height || undefined });

    // 表格搜索参数
    let params = [];

    /**
     * 加载表格数据
     * @param {*} current 
     * @param {*} size 
     */
    const onReloadHandler = (current, size) => {
        onReload(getQuery(current, size));
    }

    /**
     * 重置搜索参数
     * @param {*} field 字段名
     * @param {*} value 值
     * @param {*} expr 表达式
     */
    const resetParams = (field, value, expr) => {
        if (!field) return;  // 如果没有字段名则直接返回

        if (value !== undefined || value !== null) {
            let param = {
                field: field,
                expr: expr || 'EQ',
                value: value,
            }
            let index = params.findIndex(param => param.field === field);
            // 如果有值，则更新或添加参数
            if (index >= 0) {
                // 存在则替换
                params[index] = param;
            } else {
                // 不存在则新增
                params.push(param);
            }
        } else {
            // 如果值为空，则移除该参数
            params = params.filter(param => param.field !== field);
        }
    }

    /**
     * 搜索输入框改变事件
     * @param {*} event 
     */
    const onInputChange = (event) => {
        event.stopPropagation();
        resetParams(event.target.name, event.target.value, 'LIKE_LEFT');
    }

    // 搜索方法
    const onSearchChange = (field = undefined, value = undefined) => {
        if (field) {
            resetParams(field, value, 'EQ');
        }
        onReloadHandler(1, pagination.size);
    }

    /**
     * 表格列的默认属性，主要是搜索功能
     * @param {*} props 
     * @returns 
     */
    const columnProps = (props) => {
        if (!props || props.title === '#') {
            return props;
        }
        // 配置了width，就用用户配置的值；没有配置，则用默认的150；配置了auto，则用自动宽度
        props.width = props.width || 150;
        if (!props.search) {
            return props;
        }
        // 不配置search属性，即可自定义搜索功能
        return ({
            ...props,
            filterIcon: () => {
                let filtered = params.findIndex(param => param.field === props.key) >= 0;
                return <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
            },
            filterDropdown: () => (
                <div style={{ padding: 5, width: props.width === 'auto' ? undefined : props.width - 6 }} onKeyDown={e => e.stopPropagation()}>
                    {props.search === 'default' && (
                        <Input.Search
                            placeholder={'请输入' + props.title}
                            name={props?.key}
                            allowClear
                            onChange={onInputChange}
                            onPressEnter={() => onSearchChange(undefined, undefined)}
                            onClear={() => onSearchChange(props.key, undefined)}
                            style={{ width: '100%' }}
                            enterButton={
                                <Button
                                    type="text"
                                    size="small"
                                    style={{
                                        width: 20,
                                        border: '1px solid #d9d9d9',  // 添加边框
                                    }}
                                    onClick={() => onSearchChange(undefined, undefined)}
                                    icon={<SearchOutlined />}
                                />
                            }
                        />
                    )}
                    {props.search === 'date' && (
                        <DatePicker
                            allowClear
                            placeholder={'请选择' + props.title}
                            onChange={(date, value) => onSearchChange(props.key, value)}
                            style={{ width: '100%' }}
                        />
                    )}
                    {props.search === 'time' && (
                        <TimePicker
                            allowClear
                            placeholder={'请选择' + props.title}
                            onChange={(time, value) => onSearchChange(props.key, value)}
                            style={{ width: '100%' }}
                        />
                    )}
                    {props.search === 'datetime' && (
                        <DatePicker
                            allowClear
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder={'请选择' + props.title}
                            onChange={(time, value) => onSearchChange(props.key, value)}
                            style={{ width: '100%' }}
                        />
                    )}
                    {props.search === 'selected' && (
                        <Select
                            allowClear
                            placeholder={'请选择' + props.title}
                            onSelect={(value) => onSearchChange(props.key, value)}
                            onClear={() => onSearchChange(props.key, undefined)}
                            style={{ width: '100%' }}
                            options={props.options}
                        >
                        </Select>
                    )}
                </div>
            )
        });
    }

    /**
     * 初始化表格列的功能
     */
    const initSearch = () => {
        let list = [];
        if (columns?.length > 0) {
            list = columns.map(item => columnProps(item));
        }
        setItems(list);
    };

    /**
     * 构建查询参数
     * @param {*} current 
     * @param {*} size 
     * @returns 
     */
    const getQuery = (current, size) => ({
        params: params,
        selected: {},
        sorts: [],
        ...(isPage && { pageNo: current, pageSize: size })
    });

    /**
     * 清空搜索条件
     */
    const onClearQuery = () => {
        // TODO 清空搜索条件后，页面上还是会展示搜索条件
        params = [];
        onReloadHandler(1, pagination.size);
    }

    // 复选框
    const selection = {
        align: "center",
        fixed: true,
        columnWidth: 50,
        checkStrictly: true,
        selectedRowKeys: selected,
        onChange: resetSelected,
    };

    /**
     * 表格树状行展开后，滚动条计算
     */
    const expandable = {
        indentSize: 15,
        onExpand: (expand, row) => {
            let currentCount = count || data?.length;
            let length = row.children?.length || 0;
            showScroll(expand ? currentCount + length : currentCount - length);
        }
    }

    const showScroll = (total = 0) => {
        setCount(total);
        setScroll({ ...scroll, y: total > 12 ? 'calc(100vh - 273px)' : undefined });
    }

    useEffect(() => {
        initSearch();
    }, []);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
            {/* 顶部工具栏容器 */}
            {showTools && (
                <div style={{ display: 'flex', justifyContent: 'space-between', margin: '6px 8px' }}>
                    {/* 左侧工具栏 */}
                    <Space>
                        <div>
                            {tools && typeof tools === 'function' ? tools() : tools}
                        </div>
                    </Space>

                    {/* 右侧操作按钮 */}
                    <Space>
                        <Tooltip title="刷新">
                            <Button type="text" size='small' shape="circle" icon={<ReloadOutlined />} onClick={() => onReload()} />
                        </Tooltip>
                        <Tooltip title="清空搜索条件">
                            <Button type="text" size='small' shape="circle" icon={<ClearOutlined />} onClick={onClearQuery} />
                        </Tooltip>
                        <Tooltip title="设置">
                            <Button type="text" size='small' shape="circle" icon={<SettingOutlined />} disabled />
                        </Tooltip>
                    </Space>
                </div>
            )}
            {/* 中间表格容器 */}
            <div style={{ flex: 1, margin: '4px 0', overflow: 'hidden' }}>
                <Table
                    bordered
                    rowKey="id"
                    size='small'
                    columns={items}
                    dataSource={data}
                    pagination={false}
                    rowSelection={selection}
                    expandable={expandable}
                    scroll={scroll}
                />
            </div>

            {/* 底部分页工具栏容器 */}
            {isPage && (
                <div style={{ marginTop: 6 }}>
                    <Pagination
                        align="end"
                        showSizeChanger
                        showQuickJumper
                        size='small'
                        total={pagination.total}
                        pageSize={pagination.size}
                        current={pagination.current}
                        pageSizeOptions={[10, 20, 50]}
                        onChange={onReloadHandler}
                        showTotal={total => `共 ${total} 条`}
                    />
                </div>
            )}
        </div>
    );
}

export default CloudTable;